package p21_参数解析器;

import cn.hutool.core.text.AntPathMatcher;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockPart;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 返回一个模拟对象
 */
public class MockRequest {
    public static HttpServletRequest mockRequest() {
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setParameter("name1", "狗剩");
        request.setParameter("name2", ",lisi");
        request.addPart(new MockPart("file", "abc", "hello".getBytes(StandardCharsets.UTF_8)));
        /**
         * 针对@PathVariable的情况，处理器映射器会将真的请求uri和@PathVariable的参数建立起一个映射
         * 并转换为一个map，放入request作用域。后续的PathVariable参数解析器会获取这个map，并根据PathVariable的参数找到对应的值，并赋值给方法参数
         * 由于本次测试没有用到处理器映射器，就手动处理map
         */
        Map<String, String> map = new AntPathMatcher().extractUriTemplateVariables("/test/{id}", "/test/123");
        //System.out.println(map); 打印结果 {id=123}
        request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, map);

        request.setContentType("application/json");
        request.setCookies(new Cookie("token", "123456"));
        request.setParameter("name", "张三");
        request.setParameter("age", "18");
        String content = "{\"name\":\"里斯\",\"age\":\"23\"}";
        request.setContent(content.getBytes(StandardCharsets.UTF_8));

        return new StandardServletMultipartResolver().resolveMultipart(request);
    }
}
